package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Article;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：fish
 * @Date：2023/4/12 9:28
 * 所有文章的列表页
 */
@WebServlet("/artlist")
public class ArticleListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Article> data = new ArrayList<>();
        String msg = "未知错误！";
        //1.获取前端参数，并效验
        String currPage = req.getParameter("cp");
        String pageSize = req.getParameter("ps");
        int cp = 1;  //当前的页码
        int ps = 2;  //每页显示最大条数
        if (!StrUtil.isBlank(currPage)) {
            cp = Integer.valueOf(currPage);
        }
        if (!StrUtil.isBlank(pageSize)) {
            ps = Integer.valueOf(pageSize);
        }
        //2.使用分页查询，查询数据库得到数据
        Connection connection = DBUtils.getConnection();
        String sql = "select * from article order by aid desc limit ? offset ?;";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,ps);
        statement.setInt(2,(cp - 1) * ps);
        //执行器开始执行
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            //如果还有下一行，就创建文章表继续执行
            Article article = new Article();
            article.setAid(resultSet.getInt("aid"));
            article.setTitle(resultSet.getString("title"));
            String ctime = resultSet.getString("createtime");
            article.setCreatetime(ctime.substring(0,ctime.lastIndexOf(".")));
            String context = resultSet.getString("context");
            context = context.replace("#","");
            int maxSize = Integer.min(50,context.length());
            article.setDesc(context.substring(0,maxSize));
            data.add(article);
        }
        msg = "";
        DBUtils.close(resultSet,statement,connection);
        //3.将数据返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
